from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import db
from info.constants import CLICK_RANK_MAX_NEWS
from info.models import News, User, Comment, CommentLike
from info.utils.common import user_status_monitoring
from info.utils.response_code import RET
from . import news_url


@news_url.route('/<int:sss>')
@user_status_monitoring
def detalis_news(sss):
    # 新闻排行
    news = []
    try:
        news = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 2.出去查询的数据
    new_list = []
    for new in news:
        new_list.append(new.to_basic_dict())

    user = g.user

    # 新闻详情
    detalis_news = None
    try:
        detalis_news = News.query.get(sss)
    except Exception as e:
        current_app.logger.error(e)

    if not detalis_news:
        abort(404)

    detalis_news.clicks += 1

    # 判断是否收藏 is_collected = False表示没收藏 True表示收藏
    is_collected = False
    if user:
        if detalis_news in user.collection_news:
            is_collected = True

    # 新闻的全部评论
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == sss).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    # 查询用户是否收藏了该评论
    comment_like_lists = []
    comment_like_list_id = []
    if user:
        try:
            comment_id_lis = [comment.id for comment in comments]  # 当前新闻所有评论的ID
            # 该用户在当前新闻详情也所有的点赞列表
            comment_like_lists = CommentLike.query.filter(CommentLike.comment_id.in_(comment_id_lis),
                                                          CommentLike.user_id == user.id).all()
        except Exception as e:
            current_app.logger.error(e)

        comment_like_list_id = [comment_like_list.comment_id for comment_like_list in comment_like_lists]

    comment_dict_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        # 默认是没点赞的
        comment_dict['is_like'] = False
        if user:
            if comment.id in comment_like_list_id:
                comment_dict['is_like'] = True
        comment_dict_list.append(comment_dict)

    # 设置属性确认是否是关注的用户
    is_followed = False
    # 如果该新闻存在作者并且有登陆
    if detalis_news.user and user:
        if detalis_news.user in user.followed:
            is_followed = True

    data = {
        'user': user.to_dict() if user else None,  # 当前登陆的用户
        'new_list': new_list,  # 新闻排名
        'detalis_news': detalis_news.to_dict(),  # 当前的新闻详情
        'is_collected': is_collected,  # 是否收藏
        'is_followed': is_followed,  # 是否关注
        'comments': comment_dict_list  # 当前新闻的评论
    }

    return render_template('news/detail.html', data=data)


@news_url.route('/news_collect', methods=['POST'])
@user_status_monitoring
def collect_news():  # 用户收藏文章
    # 获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')

    # 取出新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        abort(404)
        return jsonify(errno=RET.DBERR, errmsg='新闻不存在')

    user = g.user
    # 判断是否有用户登陆
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    if action == 'collect':  # 如果是收藏操作
        if news not in user.collection_news:
            user.collection_news.append(news)
        return jsonify(errno=RET.OK, errmsg='收藏成功')
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
        return jsonify(errno=RET.OK, errmsg='取消收藏成功')


@news_url.route('/news_comment', methods=['POST'])
@user_status_monitoring
def comment_news():
    # 1.获取参数（评论内容，被评论的新闻ID,回复的评论的ID）
    news_id = request.json.get('news_id')
    comment = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    # 2.校验参数
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    if not all([news_id, comment]):
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    # 查询新闻是否存在
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        abort(404)
        return jsonify(errno=RET.DBERR, errmsg='新闻不存在')

    # 3.数据库操作
    comments = Comment()
    comments.news_id = news_id
    comments.content = comment
    comments.user_id = user.id
    if parent_id:
        comments.parent_id = parent_id
    try:
        db.session.add(comments)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    # 4.返回结果
    return jsonify(errno=RET.OK, errmsg='评论成功', comments=comments.to_dict())


@news_url.route('/comment_like', methods=['POST'])
@user_status_monitoring
def comment_like():
    # 1.获取参数
    comment_id = request.json.get('comment_id')
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    # 2.校验参数
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    if action not in ['add', 'remove']:
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')

    comment = None
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not comment:
        abort(404)
        return jsonify(errno=RET.DBERR, errmsg='评论不存在')

    if user:
        # 3.点赞的数据库里面添加

        if action == 'add':
            commentlike = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                   CommentLike.user_id == user.id).first()
            if not commentlike:
                commentlike = CommentLike()
                commentlike.comment_id = comment_id
                commentlike.user_id = user.id
                db.session.add(commentlike)
                comment.like_count += 1

        else:
            commentlike = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                   CommentLike.user_id == user.id).first()
            if commentlike:
                db.session.delete(commentlike)
                comment.like_count -= 1

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.IOERR, errmsg='操作失败')

    return jsonify(errno=RET.OK, errmsg='操作成功')


@news_url.route('/followed_user', methods=['POST'])
@user_status_monitoring
def followed_user():
    user_id = request.json.get('user_id')  # 作者的ID
    action = request.json.get('action')

    # 校验参数
    if not all([user_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    try:
        user_id = int(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')

    if action not in ['follow', 'unfollow']:
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')

    # 取出新闻
    author = None
    try:
        author = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not author:
        abort(404)
        return jsonify(errno=RET.DBERR, errmsg='用户不存在')

    user = g.user
    # 判断是否有用户登陆
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    if action == 'follow':  # 如果是收藏操作
        if author not in user.followed:
            user.followed.append(author)
        return jsonify(errno=RET.OK, errmsg='收藏成功')
    else:
        if author in user.followed:
            user.followed.remove(author)
        return jsonify(errno=RET.OK, errmsg='取消收藏成功')
